package com.jsmtr.rms.controller;

import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.jsmtr.rms.entity.*;
import com.jsmtr.rms.entity.vo.PassStateStatisticVo;
import com.jsmtr.rms.utils.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jsmtr.rms.service.ISysAdminService;
import com.jsmtr.rms.service.IUtilService;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
public class IndexController {

    @Resource
    private IUtilService utilService;

    @Resource
    private ISysAdminService sysAdminService;

    //登录页面
    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    //发送手机验证码
    @RequestMapping(value = "/SendVCode", method = RequestMethod.POST)
    public void SendVCode(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        try {

            BaseUser usr = sysAdminService.getUser(request.getParameter("username").trim());
            BaseMessageConfig messageConfig = utilService.getMessageConfig();
            if (usr == null) {
                utilService.printJsonResult(false, "员工号错误,请重新输入!", "no", response);
            }
            String tel = usr.getUtel();
            if (tel != null) {
                String vcode = StringTools.getRandNum(6);
                //System.out.println(vcode);
                Boolean sendSuccess = PhoneTools.sendMsg(tel, "招聘系统登录验证码：" + vcode, messageConfig.getUsername(), messageConfig.getPassword(), messageConfig.getHost());
                // Boolean  sendSuccess=true;
                if (sendSuccess) {
                    session.setAttribute(RightInterceptor.SEESION_USERVCODE, usr.getUcode() + "-" + vcode);
                    utilService.printJsonResult(true, "验证码已发送到你尾号为" + tel.substring(7) + "的手机", "no", response);
                } else {
                    utilService.printJsonResult(false, "验证码发送失败，请联系管理员", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "未找到你的手机号，请联系管理员", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "验证码发送失败，请联系管理员", "no", response);
        }
    }

    //登录事件
    @RequestMapping(value = "/loginSys", method = RequestMethod.POST)
    public void loginSys(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        String vcode = request.getParameter("vcode");
        String msgvcode = request.getParameter("msgvcode");
        Object uservocode = request.getSession().getAttribute(RightInterceptor.SEESION_USERVCODE);
        Object validcode = request.getSession().getAttribute("validcode");
        String lvcode = "";
        if (StringTools.trimNotEmpty(vcode)) {
            lvcode = vcode.toLowerCase();
        }

        String loginType = request.getParameter("loginType");
        if (loginType.equalsIgnoreCase("pwd")) {
            if (lvcode.equals(validcode)) {
                try {
                    BaseUser usr = sysAdminService.getUser(request.getParameter("username").trim());

                    String pwd = StringTools.GetMD5Code(request.getParameter("password").trim());
                    if (usr == null) {
                        utilService.printJsonResult(false, "该用户不存在！", "no", response);
                    } else {
                        if (usr.getUstate().equals(1)) {//20190422 新增账号启用判断
                            utilService.printJsonResult(false, "该用户已禁用,请联系管理人员！", "no", response);
                        }
                        if (usr.getUpwd().equals(pwd)) {
                            session.setAttribute(RightInterceptor.SEESION_MEMBER, usr);

                            List<String> rights = new ArrayList<String>();
                            List<BaseUserRole> uroles = sysAdminService.getBaseUserRoles(usr.getId());
                            for (BaseUserRole urole : uroles) {
                                List<BaseModular> modulars = sysAdminService.getBaseModulars(urole.getRoleid());
                                for (BaseModular modular : modulars) {
                                    rights.add(modular.getMurl());
                                    //System.out.println(modular.getMurl());
                                }
                                List<String> mfunctions = sysAdminService.getBaseModularFunctions(urole.getRoleid());
                                for (String mfunction : mfunctions) {
                                    rights.add(mfunction);
                                    //System.out.println(mfunction);
                                }
                            }
                            System.out.println(rights.contains("/Do/ZZSigning/"));
                            session.setAttribute(RightInterceptor.SEESION_RIGHT, rights);

                            utilService.printJsonResult(true, "登录成功！", request.getContextPath() + "/", response);
                        } else {
                            utilService.printJsonResult(false, "密码输入错误！", "no", response);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    utilService.printJsonResult(false, "登录失败！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "验证码输入错误！", "no", response);
            }
        } else if (loginType.equalsIgnoreCase("msg")) {
            if (uservocode.toString().indexOf(msgvcode) > 0) {
                try {
                    BaseUser usr = sysAdminService.getUser(request.getParameter("username").trim());

                    if (usr == null) {
                        utilService.printJsonResult(false, "该用户不存在！", "no", response);
                    } else {
                        if (usr.getUstate().equals(1)) {//20190422 新增账号启用判断
                            utilService.printJsonResult(false, "该用户已禁用,请联系管理人员！", "no", response);
                        }
                        String pwd = StringTools.GetMD5Code(request.getParameter("password").trim());

                        if (usr.getUpwd().equals(pwd)) {
                            session.setAttribute(RightInterceptor.SEESION_MEMBER, usr);
                            List<String> rights = new ArrayList<String>();
                            List<BaseUserRole> uroles = sysAdminService.getBaseUserRoles(usr.getId());
                            for (BaseUserRole urole : uroles) {
                                List<BaseModular> modulars = sysAdminService.getBaseModulars(urole.getRoleid());
                                for (BaseModular modular : modulars) {
                                    rights.add(modular.getMurl());
                                    //System.out.println(modular.getMurl());
                                }
                                List<String> mfunctions = sysAdminService.getBaseModularFunctions(urole.getRoleid());
                                for (String mfunction : mfunctions) {
                                    rights.add(mfunction);
                                    //System.out.println(mfunction);
                                }
                            }
                            session.setAttribute(RightInterceptor.SEESION_RIGHT, rights);
                            utilService.printJsonResult(true, "登录成功！", request.getContextPath() + "/", response);
                        } else {
                            utilService.printJsonResult(false, "密码或短信验证码输入错误！", "no", response);
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    utilService.printJsonResult(false, "登录失败！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "验证码输入错误！", "no", response);
            }
        }


    }

    //系统首页
    @RequestMapping("/")
    public String Index() {
        return "/index/index";
    }

    //系统顶部
    @RequestMapping("/header")
    public String Header(HttpServletRequest request, Model model) {
        try {
            model.addAttribute("user", utilService.getSessionUser(request).getUname());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/index/header";
    }

    //退出登录事件
    @RequestMapping(value = "/loginout", method = RequestMethod.POST)
    public void loginout(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        try {
            session.removeAttribute(RightInterceptor.SEESION_MEMBER);
            session.removeAttribute(RightInterceptor.SEESION_RIGHT);
            utilService.printJsonResult(true, "退出成功", "/login", response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败", "/login", response);
        }
    }

    //系统菜单页
    @RequestMapping("/menu")
    public String Menu(HttpServletRequest request, Model model) {
        try {
            StringBuilder menu = new StringBuilder();
            BaseUser usr = utilService.getSessionUser(request);
            List<BaseUserRole> uroles = sysAdminService.getBaseUserRoles(usr.getId());
            List<BaseModular> pmodulars = new ArrayList<BaseModular>();//一级菜单
            List<BaseModular> smodulars = new ArrayList<BaseModular>();//二级菜单
            for (BaseUserRole urole : uroles) {
                List<BaseModular> modulars = sysAdminService.getBaseModulars(urole.getRoleid());
                for (BaseModular modular : modulars) {
                    if (modular.getParentid() == 0) {
                        boolean hasp = false;
                        for (BaseModular _pmodular : pmodulars) {
                            if (_pmodular.getId().equals(modular.getId())) {
                                hasp = true;
                                break;
                            }
                        }
                        if (!hasp) {
                            pmodulars.add(modular);
                        }
                    } else {
                        boolean hass = false;
                        for (BaseModular _smodular : smodulars) {
                            if (_smodular.getId().equals(modular.getId())) {
                                hass = true;
                                break;
                            }
                        }
                        if (!hass) {
                            smodulars.add(modular);
                        }
                        if (modular.getParentid() == 50) {
                            System.out.println(modular.toString());
                        }
                    }
                }
            }

            //排序
            Collections.sort(pmodulars, new Comparator<BaseModular>() {
                public int compare(BaseModular m1, BaseModular m2) {
                    return m1.getMorder().compareTo(m2.getMorder());
                }
            });

            for (BaseModular pmodular : pmodulars) {
                menu.append("<a class='m' target='rightfrm'  href='"
                        + pmodular.getMurl() + "'><span class='a"
                        + pmodular.getMorder() + "'>" + pmodular.getMname()
                        + "</span></a>");

                List<BaseModular> tmodulars = new ArrayList<BaseModular>();
                for (BaseModular smodular : smodulars) {
                    if (smodular.getParentid().equals(pmodular.getId())) {
                        tmodulars.add(smodular);
                    }
                }

                if (tmodulars.size() > 0) {
                    menu.append("<div class='submenu'>");

                    //排序
                    Collections.sort(tmodulars, new Comparator<BaseModular>() {
                        public int compare(BaseModular m1, BaseModular m2) {
                            return m1.getMorder().compareTo(m2.getMorder());
                        }
                    });

                    for (BaseModular tmodular : tmodulars) {
                        menu.append("<a target='rightfrm' href='" + tmodular.getMurl() + "'><span>" + tmodular.getMname() + "</span></a>");
                    }

                    menu.append("</div>");
                }
            }


            model.addAttribute("menu", menu);
            model.addAttribute("user", utilService.getSessionUser(request).getUname());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/index/menu";
    }

    //待办业务
    @RequestMapping("/start")
    @SuppressWarnings("unchecked")
    public String Start(HttpServletRequest request, Model model) {
        try {
//            StringBuilder str = new StringBuilder();
            List<Long> total = utilService.getTotalHumanNumber();
            List<Object[]> data = utilService.getAnnualHumanNumber();
            List<ProjectInfo> proList = sysAdminService.getProjectInfo();

            List<String> years = new ArrayList<>();
            List<Integer> passed = new ArrayList<>();
            List<Integer> unpassed = new ArrayList<>();
            List<String> yearList = utilService.distinctProjectYear();
//            for (String s :
//                    yearList) {
//                if (s != null) {
//                    years.add(s);
//                }
//            }
            for (Object[] d :
                    data) {
                if (d[0] == null) {
                    continue;
                }
                String d0 = (String) d[0];
                if (!years.contains(d0)) {
                    years.add((d0));
                    passed.add(0);
                    unpassed.add(0);
                }
            }

//            str.append("<tr><td class='link'><a href=''>这里是我的代办业务信息</a></td></tr>");
//            model.addAttribute("links", str);
            model.addAttribute("total", JSONArray.fromObject(total).toString());
            model.addAttribute("years", JSONArray.fromObject(years).toString());
            model.addAttribute("yearList", years);
            model.addAttribute("passed", JSONArray.fromObject(passed).toString());
            model.addAttribute("unpassed", JSONArray.fromObject(unpassed).toString());
            model.addAttribute("proList", proList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/index/start";
    }

    //[start] 统计信息
    @ResponseBody
    @RequestMapping(value = "/chartB")
    @SuppressWarnings("unchecked")
    public void start(HttpServletResponse response, @RequestParam String proid, @RequestParam String year) {
        try {
            List<PassStateStatisticVo> passlist = new ArrayList<>();
            List<Object[]> resultList = utilService.passStateStatistic(proid, year);
            for (Object[] result :
                    resultList) {
                BigDecimal bigDecimal = (BigDecimal)result[0];
                PassStateStatisticVo vo = new PassStateStatisticVo(bigDecimal.intValue(), (String)result[1],
                        (String)result[2], (String)result[3], (String)result[4], (String)result[5], (String)result[6],
                        (String)result[7], (String)result[8], (String)result[9]);
                passlist.add(vo);
            }
            List<String> nodes = new ArrayList<>();
            List<Integer> passed = new ArrayList<>();
            List<Integer> unpassed = new ArrayList<>();
            for (PassStateStatisticVo statisticVo :
                    passlist) {
                String name = statisticVo.getFname();
                if (!nodes.contains(name)) {
                    nodes.add(name);
                    passed.add(0);
                    unpassed.add(0);
                }
                int index = nodes.indexOf(name);
                getCount(statisticVo, index, passed, unpassed);
            }
            PrintWriter writer = response.getWriter();
            response.setContentType("application/json;charset='UTF-8'");
            JSONObject ret = new JSONObject();
            ret.put("xAxis", JSONArray.fromObject(nodes));
            ret.put("passed", JSONArray.fromObject(passed));
            ret.put("unPassed", JSONArray.fromObject(unpassed));
            writer.write(ret.toString());
        } catch (Exception exception) {

            exception.printStackTrace();
        }
    }

    private void getCount(PassStateStatisticVo statisticVo, int index, List<Integer> passed, List<Integer> unpassed) throws Exception {
        String fname = statisticVo.getFname();
        if ("资料审核".equals(fname)) {
            getPassedOrUnpassed(statisticVo.getZlstate(), "审核通过", passed, unpassed, index);
        } else if ("面试".equals(fname)) {
//            List<Object[]> res = sysAdminService.getMsCount(year);
//            for (Object[] itm :
//                    res) {
//                if ("通过".equals(itm[0])) {
//                    passedAndUnpassed[0] += ((BigDecimal) itm[1]).intValue();
//                } else {
//                    passedAndUnpassed[1] += ((BigDecimal) itm[1]).intValue();
//                }
//            }
            getPassedOrUnpassed(statisticVo.getMsresult(), "通过", passed, unpassed, index);
        } else if ("背景调查".equals(fname)) {
//            List<Object[]> res = sysAdminService.getCount("zsstate", year);
//            getPassedOrUnpassed(passedAndUnpassed, res, "合格");
            getPassedOrUnpassed(statisticVo.getZsstate(), "通过", passed, unpassed, index);

        } else if ("签约".equals(fname)) {
            //todo
        } else if ("录用".equals(fname)) {
//            List<Object[]> res = sysAdminService.getCount("bdstate", year);
//            getPassedOrUnpassed(passedAndUnpassed, res, "合格");
            getPassedOrUnpassed(statisticVo.getBdstate(), "通过", passed, unpassed, index);

        } else if ("笔试".equals(fname)) {
//            List<Object[]> res = sysAdminService.getBsCount(year);
//            for (Object[] itm :
//                    res) {
//                if ("通过".equals(itm[0]) || "已通过".equals(itm[0]) || "推荐".equals(itm[0]) ||
//                        "合格".equals(itm[0]) || "已合格".equals(itm[0])) {
//                    passedAndUnpassed[0] += ((BigDecimal) itm[1]).intValue();
//                } else {
//                    passedAndUnpassed[1] += ((BigDecimal) itm[1]).intValue();
//                }
//            }
            getPassedOrUnpassed(statisticVo.getBsresult(), "通过", passed, unpassed, index);
        } else if ("简历筛选".equals(fname)) {
//            List<Object[]> res = sysAdminService.getCount("state", year);
//            getPassedOrUnpassed(passedAndUnpassed, res, "合格");
            getPassedOrUnpassed(statisticVo.getState(), "通过", passed, unpassed, index);

        } else if ("体检".equals(fname)) {
//            List<Object[]> res = sysAdminService.getCount("tjstate", year);
//            getPassedOrUnpassed(passedAndUnpassed, res, "合格");
            getPassedOrUnpassed(statisticVo.getTjstate(), "通过", passed, unpassed, index);

        }
//        return passedAndUnpassed;
    }

    private void getPassedOrUnpassed(String state, String difference, List<Integer> passed, List<Integer> unpassed
            , int index) {
        if (difference.equals(state) || "已通过".equals(state) || "通过".equals(state)
                || "已合格".equals(state)) {
            passed.set(index, passed.get(index) + 1);
        } else {
            unpassed.set(index, unpassed.get(index) + 1);
        }
    }

    //[end]

    //非法访问
    @RequestMapping("/illegal")
    public String illegal() {
        return "/illegal";
    }

    @RequestMapping("/ssologin")
    @SuppressWarnings("unchecked")
    public String ssologin(@RequestParam String code, HttpSession session) {
        try {
            String ucode = DESUtil.decrypt(code);
            List<Object[]> users = sysAdminService.getUserByUcode(ucode);
            if (users != null) {
                for (Object[] user :
                        users) {
                    String name = (String) user[3];
                    if ("集团领导".equals(name) || "各部门招聘专员".equals(name) || "集团人力资源部招聘专员".equals(name)) {
                        //session写入权限
                        BaseUser usr = sysAdminService.getUser((String) user[1]);
                        List<BaseUserRole> uroles = sysAdminService.getBaseUserRoles(usr.getId());
                        List<String> rights = new ArrayList<String>();
                        for (BaseUserRole urole : uroles) {
                            List<BaseModular> modulars = sysAdminService.getBaseModulars(urole.getRoleid());
                            for (BaseModular modular : modulars) {
                                rights.add(modular.getMurl());
                            }
                            List<String> mfunctions = sysAdminService.getBaseModularFunctions(urole.getRoleid());
                            rights.addAll(mfunctions);
                        }

                        session.setAttribute(RightInterceptor.SEESION_MEMBER, usr);
                        session.setAttribute(RightInterceptor.SEESION_RIGHT, rights);
                        break;
                    }
                }

                return "redirect:/";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "illegal";
    }

}
